import React, { Component, Fragment } from 'react'  
import TodoItem from './TodoItem'
import axios from 'axios'
// import Test from './Test'
import './style.css'

export default class App extends Component {

  constructor(props){
    super(props)
    this.state = {
        inputValue:'',
        list:[]
    }
    this.handleInputChange = this.handleInputChange.bind(this)
    this.handleButtonClick = this.handleButtonClick.bind(this)
    this.handleItemDelete  = this.handleItemDelete.bind(this)
  }
  
  //  挂载完成 (只执行一次)  
  componentDidMount(){
    // console.log('componentDidMount'); 
    axios.get('/api/todolist').then((res)=>{
      // let list = res.data 
      // this.setState(()=>{
      //   return {
      //     list 
      //   }
      // })

      this.setState(()=>({
        list:[...res.data]
      }))
    }).catch((err)=>{
        console.log(err);
    })

  }

  //  更新完成之后
  // componentDidUpdate(){
  //   console.log('componentDidUpdate');
  // }

  // shouldComponentUpdate(){
  //   console.log('shouldComponentUpdate');
  //   return true;
  // }
  
  // componentWillUnmount(){
  //   console.log('componentWillUnmount');
  // }
   
  render() {  
    return ( 
      <Fragment>
         <div>   
            <label htmlFor="insertArea">输入内容</label>
            <input id="insertArea" 
            className="input" 
            type="text" value={this.state.inputValue}
            onChange= {this.handleInputChange} 
            ref = {(input)=>{this.input = input}}
            /> 
            <button onClick={this.handleButtonClick}>提交</button>
          </div>
         <ul ref={ul => {this.ul = ul}}>{this.getTodoItem()}</ul>
         {/* <Test content={this.state.inputValue}/> */}
      </Fragment>
    )
  }

  getTodoItem(){
    return this.state.list.map((item,index)=>{
      return  <TodoItem 
        index={index}   
        key={index} 
        content={item}  
        deleteItem= {this.handleItemDelete} /> 
   })
  }
 
  handleInputChange(e){ 
    // const inputValue = e.target.value 
    const inputValue =this.input.value; 
    this.setState(()=> ({
        inputValue
    }))  
  }

  handleButtonClick(){  
    this.setState((prevState)=>{
      return {
        list: [...prevState.list,prevState.inputValue],
        inputValue:''
      }
    },()=>{
      console.log(this.ul.querySelectorAll('div').length);
    }) 
 
  }

  handleItemDelete(index){ 
    this.setState((prevState)=>{
      let list = [...prevState.list] 
      list.splice(index,1)
      return {
        list 
      }
    }) 
  }

}
